using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using SmartLink.DTOS.SysBasic;
using SmartLink.Application.IServices;
using SmartLink.Domain;
using SmartLink.Domain.Entity;
using SmartLink.Infrastructure;
using SmartLink.Infrastructure.Cache;
using System.Text;
using System.IO;
using SmartLink.Application.Services;
using SmartLink.EnumLibrary;
using SmartLink.DTOS;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Net.Http;
using System.Net;

namespace SmartLink.WebApi.Controllers
{
    public class BaseAPIControl : ApiController
    {
        public BaseAPIControl()
        {
        }


        /// <summary>
        /// 用户信息
        /// </summary>
        public CurrentUserInfo CurUserInfo
        {
            get
            {
                var token = HttpContext.Current.Request.Headers["token"];
                var userInfo = UserInfoCaches.GetUserInfoCache(token);
                return userInfo;
            }
        }

        public int CurUserId
        {
            get
            {
                var token = HttpContext.Current.Request.Headers["token"];
                int userId = JWTHelper.GetUserIdFromToken(Token);
                return userId;
            }
        }

        /// <summary>
        /// Token
        /// </summary>
        public string Token
        {
            get
            {
                var token = HttpContext.Current.Request.Headers["token"];
                return token;
            }
        }

        /// <summary>
        /// 导出xls表格
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="fileName">导出文件名，不需要后缀</param>
        protected void ExportXls(MemoryStream stream, string fileName)
        {
            var httpResponse = HttpContext.Current.Response;
            httpResponse.Clear();
            httpResponse.Buffer = true;
            httpResponse.Charset = Encoding.UTF8.BodyName;
            httpResponse.AppendHeader("Content-Disposition", $"attachment;filename={fileName}.xlsx");
            httpResponse.AppendHeader("Access-Control-Allow-Origin", "*");
            httpResponse.ContentEncoding = Encoding.UTF8;
            httpResponse.ContentType = "application/vnd.ms-excel; charset=UTF-8";
            var newMs = new MemoryStream(stream.ToArray());
            newMs.WriteTo(httpResponse.OutputStream);
            httpResponse.End();
            stream.Dispose();
        }
        /// <summary>
        /// 检查上传文件
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        protected bool CheckUpload(ref HttpResponseMessage response)
        {
            if (HttpContext.Current.Request.Files.Count > 0)
            {
                var files = HttpContext.Current.Request.Files;
                if (files.Count == 0)
                {
                    response = Request.CreateResponse(InfrastructureAppService.Response("请选择文件", StateCodeEnum.失败));
                    return false;
                }

                long uploadLimitSize = long.Parse(ConfigurationManager.AppSettings["Max"]);
                string[] uploadLimitTypes = ConfigurationManager.AppSettings["fileTypes"].ToString().Split(',');
                for (int i = 0; i < files.Count; i++)
                {
                    var file = files[i] as HttpPostedFile;
                    if (file.ContentLength > uploadLimitSize)
                    {
                        response = Request.CreateResponse(InfrastructureAppService.Response($"上传文件单个大小超过限制：{file.FileName}", StateCodeEnum.失败));
                        return false;
                    }
                    var fileExt = file.FileName.Substring(file.FileName.LastIndexOf(".") + 1);
                    if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(uploadLimitTypes, fileExt.ToLower()) < 0)
                    {
                        response = Request.CreateResponse(InfrastructureAppService.Response($"不支持上传文件类型：{fileExt}", StateCodeEnum.失败));
                        return false;
                    }

                    string[] fileSpits = file.FileName.Split(new string[1] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
                    var pattern = new Regex("[`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]");
                    if (pattern.IsMatch(fileSpits[fileSpits.Length - 1]))
                    {
                        response = Request.CreateResponse(InfrastructureAppService.Response("文件名不能存在特殊字符", StateCodeEnum.失败));
                        return false;
                    }
                }
            }
            return true;
        }
        /// <summary>
        /// 手动验证模型（用于Multipart/form-data格式传参情况）
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="model"></param>
        /// <param name="response"></param>
        /// <returns></returns>
        protected bool ValidateModel<TModel>(TModel model, ref HttpResponseMessage response)
        {
            ModelState.Clear();
            this.Validate(model);
            if (!ModelState.IsValid)
            {
                var error = string.Empty;
                foreach (var key in ModelState.Keys)
                {
                    var state = ModelState[key];
                    if (!state.Errors.Any()) continue;
                    var firstError = state.Errors.First();
                    error = firstError.ErrorMessage;
                    if (string.IsNullOrWhiteSpace(error))
                        error = firstError.Exception?.Message;
                    break;
                }
                response = this.Request.CreateResponse(HttpStatusCode.Forbidden, new Results { State = (int)StateCodeEnum.验证报错, Message = error });
                return false;
            }
            return true;
        }
    }
}